package com.geline.mybatisplus.interceptor.inner;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.geline.mybatisplus.util.UniqueKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.SQLException;

/**
 * 注解拦截器 @UniqueKey
 *
 * @author: mx
 * @date: 2024-08-22 17:41
 */
@Slf4j
public class UniqueKeyInterceptor implements InnerInterceptor {

    private JdbcTemplate jdbcTemplate;

    public UniqueKeyInterceptor(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        SqlCommandType sct = ms.getSqlCommandType();
        if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE) {
            Object object = parameter;
            if(parameter instanceof MapperMethod.ParamMap){
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                if(map.containsKey("et")){
                    object = map.get("et");
                }else if(map.containsKey("param1")){
                    object = map.get("param1");
                }
            }
            UniqueKeyUtil.validUniqueKey(object);
        }
    }
}
